/**
 * 
 */
package org.dc.agent.job;


import org.apache.log4j.Logger;
import org.dc.agent.beans.Oid;
import org.dc.agent.beans.Policy;
import org.dc.agent.beans.Policys;
import org.dc.agent.util.DBPool;
import org.dc.agent.util.DateUtil;
import org.dc.agent.xml.XmlOper;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.*;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.Vector;

/**
 * @author 徐春鹏
 * 
 */
public class SnmpJob implements Job {
	private Logger logger = Logger.getLogger(SnmpJob.class);
	private String sql = "INSERT INTO `snmpdata`(ip,gathername,value,addtime) values(?,?,?,?)";

	// private

	@Override
	public void execute(JobExecutionContext context)
			throws JobExecutionException {
		DBPool instance = DBPool.getInstance();
		Connection connection = instance.getConnection();
		try {
			PreparedStatement prepareStatement = connection
					.prepareStatement(sql);
			// 取得snmp
			Snmp snmp = (Snmp) context.getMergedJobDataMap().get("snmp");

			Policys policys = new XmlOper().getPolicy();

			List<Policy> policylist = policys.getPolicys();
			String currentStrDate = DateUtil.getCurrentStrDate();
			for (Policy policy : policylist) {

				String ip = policy.getIp();
				String community = policy.getCommunity();
				List<Oid> oids = policy.getOids();
				for (Oid oid : oids) {
					String name = oid.getName();
					String value = oid.getValue();
					String valueFromDevice = this.getValueFromDevice(snmp, ip
							+ "/161", community, value);
					logger.warn(ip + "的 " + name + " =" + valueFromDevice);
					prepareStatement.setString(1, ip);
					prepareStatement.setString(2, name);
					prepareStatement.setString(3, valueFromDevice);
					prepareStatement.setString(4, currentStrDate);
					prepareStatement.executeUpdate();

				}

			}
			prepareStatement.close();

			connection.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * @category 获得设备的信息
	 * */
	public String getValueFromDevice(Snmp snmp, String ipAddress,
			String community, String oid) {

		PDU pdu = new PDU();
		Address targetAddress = GenericAddress.parse(ipAddress);

		CommunityTarget target = new CommunityTarget();
		target.setCommunity(new OctetString(community));
		target.setVersion(SnmpConstants.version2c);

		target.setAddress(targetAddress);

		// 通信失败的尝试次数
		target.setRetries(2);
		// 超时时间
		target.setTimeout(1500);

		pdu.add(new VariableBinding(new OID(oid)));
		pdu.setType(PDU.GETNEXT);
		ResponseEvent response = null;
		try {

			response = snmp.send(pdu, target);
			PDU responsepdu = response.getResponse();

			if (responsepdu != null) {
				Vector<? extends VariableBinding> variableBinding = responsepdu
						.getVariableBindings();
				String variableBindings = variableBinding.toString();
				int indexOf = variableBindings.indexOf("="); // 获得=的所在的位置
				int j = variableBindings.length(); // 获得整个返回的字符串的长度
				oid = variableBindings.substring(1, indexOf - 1);
				String value = variableBindings.substring(indexOf + 1, j - 1);
				System.out.println(value);
				return value;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		return "";
	}
}
